package com.xywh.emergency_outbound.mvp.ui.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.base.BaseLazyFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.LogUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xywh.emergency_outbound.R;
import com.xywh.emergency_outbound.app.EmergencyOutboundApplication;
import com.xywh.emergency_outbound.di.component.DaggerTab3Component;
import com.xywh.emergency_outbound.di.module.Tab3Module;
import com.xywh.emergency_outbound.mvp.contract.Tab3Contract;
import com.xywh.emergency_outbound.mvp.presenter.Tab3Presenter;
import com.xywh.emergency_outbound.mvp.ui.adapter.Tab3Adapter;
import com.xywh.emergency_outbound.mvp.ui.db.entity.MaterialLocal;
import com.xywh.emergency_outbound.mvp.ui.entity.OrderSuccess;
import com.xywh.emergency_outbound.mvp.ui.entity.Tab1Address;
import com.xywh.emergency_outbound.mvp.ui.entity.Tab3;
import com.xywh.emergency_outbound.mvp.ui.entity.Tab4;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import me.jessyan.armscomponent.commonsdk.utils.Utils;
import okhttp3.MediaType;
import okhttp3.RequestBody;

import static android.support.v7.widget.DividerItemDecoration.VERTICAL;
import static com.jess.arms.base.BaseConstants.MAIN_CURRENT_FOUR;
import static com.jess.arms.base.BaseConstants.MATERIAL_LOCAL;
import static com.jess.arms.base.BaseConstants.TAB_3_ADDRESS;
import static com.jess.arms.base.BaseConstants.TAB_3_RONG_HE_QU_ADDRESS;
import static com.jess.arms.base.BaseConstants.TAB_3_RONG_HE_QU_OR_QI_TA;
import static com.jess.arms.utils.Preconditions.checkNotNull;


public class Tab3Fragment extends BaseLazyFragment<Tab3Presenter> implements Tab3Contract.View, OnRefreshListener, Tab3Adapter.IItemDelete {


    private static boolean mIsNeedDemo = true;
    @BindView(R.id.empty_text)
    TextView empty_text;
    @BindView(R.id.empty_image)
    ImageView empty_image;

    @BindView(R.id.empty)
    View mEmptyLayout;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.refreshLayout)
    RefreshLayout mRefreshLayout;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.img_location)
    ImageView imgLocation;
    @BindView(R.id.tv_address_title)
    TextView tvAddressTitle;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.rl_one_touch_dialing)
    RelativeLayout rlOneTouchDialing;
    @BindView(R.id.sw_is_delivery)
    Switch swIsDelivery;
    @BindView(R.id.rl_address)
    RelativeLayout rlAddress;
    private Tab3Adapter mAdapter;
    private List<Tab3.DataBean> mDataBeanList = new ArrayList<>();


    private String mAddressId;
    private String mPersonId;

    public static Tab3Fragment newInstance() {
        Tab3Fragment fragment = new Tab3Fragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerTab3Component //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .tab3Module(new Tab3Module(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tab3, container, false);
        initToolbar(view);
        return view;
    }

    private void initToolbar(View view) {
        ToolbarUtils.initToolbarTitleNoBack(view, this, "购物车");
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        initRefreshLayout();
        initRecyclerView();
        initEmpty();
        getMaterialLocalData();

        swIsDelivery.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    rlAddress.setVisibility(View.VISIBLE);
                } else {
                    rlAddress.setVisibility(View.GONE);
                }
            }
        });
        //getTab3Data();
    }

    private void initRefreshLayout() {
        mRefreshLayout.setRefreshHeader(new ClassicsHeader(getActivity()).setSpinnerStyle(SpinnerStyle.FixedBehind).setPrimaryColorId(R.color.public_colorPrimary).setAccentColorId(android.R.color.white));
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setEnableRefresh(false);
        mRefreshLayout.autoRefresh();
        mRefreshLayout.setEnableLoadMore(false);
    }

    private void initRecyclerView() {

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), VERTICAL));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(mAdapter = new Tab3Adapter(getActivity(), mDataBeanList, EmergencyOutboundApplication.getDbController(), this));

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                Utils.navigation(getActivity(), RouterHub.SALES_CLIENT_ZUI_XIN_XIAO_XI_XIANG_QING_ACTIVITY);
            }
        });
    }

    private void initEmpty() {
        empty_image.setImageResource(R.drawable.ic_empty);
        empty_text.setTextColor(Color.parseColor("#CFCFCF"));
        empty_text.setText("暂无数据");
    }

    private void getMaterialLocalData() {
        List<MaterialLocal> materialLocals = EmergencyOutboundApplication.getDbController().searchAll();
        LogUtils.debugEInfo("新增的数据-Tab3Fragment中的materialLocals的数量是：" + materialLocals.size());


        if (materialLocals != null && materialLocals.size() > 0) {
            List<Tab3.DataBean> dataBeanList = new ArrayList<>();

            for (int i = 0; i < materialLocals.size(); i++) {
                Tab3.DataBean dataBean = new Tab3.DataBean();
                dataBean.setMaterialName(materialLocals.get(i).getMaterialName());
                dataBean.setMaterialUnit(materialLocals.get(i).getMaterialUnit());
                dataBean.setStoreId(materialLocals.get(i).getStoreId());
                dataBean.setStoreName(materialLocals.get(i).getStoreName());
                dataBean.setStoreNum(materialLocals.get(i).getStoreNum());
                dataBeanList.add(dataBean);
            }
            mDataBeanList.clear();
            mDataBeanList.addAll(dataBeanList);
            mAdapter.notifyDataSetChanged();
            mEmptyLayout.setVisibility(View.GONE);
            mRecyclerView.setVisibility(View.VISIBLE);

        } else {
            mEmptyLayout.setVisibility(View.VISIBLE);
            mRecyclerView.setVisibility(View.GONE);
        }
    }

    /**
     * 通过此方法可以使 Fragment 能够与外界做一些交互和通信, 比如说外部的 Activity 想让自己持有的某个 Fragment 对象执行一些方法,
     * 建议在有多个需要与外界交互的方法时, 统一传 {@link Message}, 通过 what 字段来区分不同的方法, 在 {@link #setData(Object)}
     * 方法中就可以 {@code switch} 做不同的操作, 这样就可以用统一的入口方法做多个不同的操作, 可以起到分发的作用
     * <p>
     * 调用此方法时请注意调用时 Fragment 的生命周期, 如果调用 {@link #setData(Object)} 方法时 {@link Fragment#onCreate(Bundle)} 还没执行
     * 但在 {@link #setData(Object)} 里却调用了 Presenter 的方法, 是会报空的, 因为 Dagger 注入是在 {@link Fragment#onCreate(Bundle)}
     * 方法中执行的
     * 然后才创建的 Presenter, 如果要做一些初始化操作,可以不必让外部调用 {@link #setData(Object)}, 在 {@link #initData(Bundle)} 中初始化就可以了
     *
     * <p>
     * Example usage:
     *
     * <pre>
     * public void setData(@Nullable Object data) {
     *     if (data != null && data instanceof Message) {
     *         switch (((Message) data).what) {
     *             case 0:
     *                 loadData(((Message) data).arg1);
     *                 break;
     *             case 1:
     *                 refreshUI();
     *                 break;
     *             default:
     *                 //do something
     *                 break;
     *         }
     *     }
     * }
     *
     * // call setData(Object):
     * Message data = new Message();
     * data.what = 0;
     * data.arg1 = 1;
     * fragment.setData(data);
     * </pre>
     *
     * @param data 当不需要参数时 {@code data} 可以为 {@code null}
     */
    @Override
    public void setData(@Nullable Object data) {

    }

    @Subscriber(tag = TAB_3_ADDRESS, mode = ThreadMode.MAIN)
    public void tab3Address(Tab4.DataBean dataBean) {
        if (dataBean != null) {
            mAddressId = String.valueOf(dataBean.getEmgConsigneeAddresses().get(0).getID());
            mPersonId = String.valueOf(dataBean.getID());
            imgLocation.setImageDrawable(getResources().getDrawable(R.drawable.icon_location));
            tvAddressTitle.setText("其他应急现场");
            tvName.setText(dataBean.getConsigneeName());
            tvPhone.setText(dataBean.getLinkPhone());
            tvAddress.setText(dataBean.getEmgConsigneeAddresses().get(0).getAddress());
        }
    }

    @Subscriber(tag = TAB_3_RONG_HE_QU_OR_QI_TA, mode = ThreadMode.MAIN)
    public void tab3RongHeQuOrQiTaAddress(Tab4.DataBean dataBean) {
        if (dataBean != null) {
            mAddressId = String.valueOf(dataBean.getEmgConsigneeAddresses().get(0).getID());
            mPersonId = String.valueOf(dataBean.getID());
            if (!TextUtils.isEmpty(dataBean.getIsMixSpot()) && dataBean.getIsMixSpot().equals("true")) {
                tvAddressTitle.setText("融合区应急物资专项调拨");
                imgLocation.setImageDrawable(getResources().getDrawable(R.drawable.icon_rong_he_qu_logo));
            } else {
                tvAddressTitle.setText("其他应急现场");
                imgLocation.setImageDrawable(getResources().getDrawable(R.drawable.icon_location));

            }
            tvName.setText(dataBean.getConsigneeName());
            tvPhone.setText(dataBean.getLinkPhone());
            tvAddress.setText(dataBean.getEmgConsigneeAddresses().get(0).getAddress());
        }
    }

    @Subscriber(tag = TAB_3_RONG_HE_QU_ADDRESS, mode = ThreadMode.MAIN)
    public void tab3RongHeQuAddress(Tab1Address.DataBean dataBean) {
        if (dataBean != null) {
            mAddressId = String.valueOf(dataBean.getID());
            mPersonId = String.valueOf(dataBean.getEmgConsignee().getID());
            imgLocation.setImageDrawable(getResources().getDrawable(R.drawable.icon_rong_he_qu_logo));
            tvAddressTitle.setText("融合区应急物资专项调拨");
            tvName.setText(dataBean.getEmgConsignee().getConsigneeName());
            tvPhone.setText(dataBean.getEmgConsignee().getLinkPhone());
            tvAddress.setText(dataBean.getAddress());
        }
    }

    @Subscriber(tag = MATERIAL_LOCAL, mode = ThreadMode.MAIN)
    public void updateMaterial(String type) {
        if (EmergencyOutboundApplication.getDbController() != null) {
            getMaterialLocalData();
        }
    }

    @Override
    public void getTab3DataSuccess(OrderSuccess entityData) {
        showMessage(entityData.getMessage());
        if (entityData.getCode() == 200) {
            EmergencyOutboundApplication.getDbController().deleteAll();
//            EventBus.getDefault().post("", "updategetTab1Data");
//            EventBus.getDefault().post(0, "tab2EmgtransferList");
            EventBus.getDefault().post("1", "setImgCartNum");
            getMaterialLocalData();

            Utils.navigation(getActivity(), RouterHub.ACTIVITY_ORDER_RELEASED);

        }

    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
//
//        mRefreshLayout.finishRefresh();
//        mEmptyLayout.setVisibility(View.GONE);

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(getActivity(), message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }

    @OnClick(R.id.rl_one_touch_dialing)
    public void onViewClicked() {
//        Utils.navigation(getActivity(), RouterHub.ACTIVITY_ORDER_RELEASED);
        getTab3Data();

    }

    private void getTab3Data() {
        List<MaterialLocal> materialLocals = EmergencyOutboundApplication.getDbController().searchAll();

        if (materialLocals != null && materialLocals.size() > 0) {
            String materialsJsonStr = "";
            for (int i = 0; i < materialLocals.size(); i++) {

                materialsJsonStr += "   {\n" +
                        "                    \"ID\": 0,\n" +
                        "                    \"EmgTransferId\": 0,\n" +
                        "                    \"OutStoreId\": " + materialLocals.get(i).getStoreId() + ",\n" +
                        "                    \"OutStoreName\": \"" + materialLocals.get(i).getStoreName() + "\",\n" +
                        "                    \"MaterialName\": \"" + materialLocals.get(i).getMaterialName() + "\",\n" +
                        "                    \"TransMaterialNum\": " + materialLocals.get(i).getStoreNum() + ",\n" +
                        "                    \"TransMaterialUnit\": \"" + materialLocals.get(i).getMaterialUnit() + "\"\n" +
                        "                },";
            }
            materialsJsonStr = ArmsUtils.cutLastString(materialsJsonStr);

            String idDelivery = "true";

            if (swIsDelivery.isChecked()) {
                idDelivery = "true";
            } else {
                idDelivery = "false";

            }

            String jsonData = "{\n" +
                    "            \"EmgConsignee\": null,\n" +
                    "            \"EmgConsigneeAddress\": null,\n" +
                    "            \"EmgTransferItems\": [\n" + materialsJsonStr +
                    "            ],\n" +
                    "            \"ID\": 0,\n" +
                    "            \"EmgConsigneeId\": " + mPersonId + ",\n" +
                    "            \"EmgConsigneeName\": \"" + tvName.getText().toString().trim() + "\",\n" +
                    "            \"Latitude\": \"" + mSharedPreferencesHelper.getString(BaseConstants.LAT) + "\",\n" +
                    "            \"Longitude\": \"" + mSharedPreferencesHelper.getString(BaseConstants.LNG) + "\",\n" +
                    "            \"EmgLinkPhone\": \"" + tvPhone.getText().toString().trim() + "\",\n" +
                    "            \"Address\": \"" + tvAddress.getText().toString().trim() + "\",\n" +
                    "            \"EmgConsigneeAddressId\": " + mAddressId + ",\n" +
                    "            \"OutStorageListBatchId\": null,\n" +
                    "            \"InsertUserId\": 0,\n" +
                    "            \"InsertDateTime\": null,\n" +
                    "            \"ModifyUserId\": null,\n" +
                    "            \"ModifyDateTime\": null\n" +
                    "}";


            RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonData);
            mPresenter.getTab3Data(body);
        } else {
            showMessage("没有可以提交的数据,请先选择物料");
//            EventBus.getDefault().post(MAIN_CURRENT_ONE, BaseConstants.SET_CURRENT_ITEM);
        }

    }

    @OnClick(R.id.rl_address)
    public void chooseAddress() {
//        Utils.navigation(getActivity(), RouterHub.ACTIVITY_ORDER_RELEASED);
        EventBus.getDefault().post("2", BaseConstants.ADDRESS_ITEM_TAG);
        EventBus.getDefault().post(MAIN_CURRENT_FOUR, BaseConstants.SET_CURRENT_ITEM);

    }

    @Override
    protected void loadData() {
        super.loadData();
//        mDbController = DbController.getInstance(getActivity());
//        List<MaterialLocal> materialLocals = mDbController.searchAll();
//        LogUtils.debugEInfo("materialLocals的数量是：" + materialLocals.size());
    }


    @Override
    public void itemDelete() {
        EventBus.getDefault().post("1", BaseConstants.MATERIAL_LOCAL);
        EventBus.getDefault().post("1", BaseConstants.SET_IMG_CART_NUM);
    }
}
